package com.hmall.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hmall.common.utils.UserContext;
import com.hmall.domain.dto.CartFormDTO;
import com.hmall.domain.po.Cart;
import com.hmall.domain.po.UserPreference;
import com.hmall.domain.vo.CartVO;
import com.hmall.service.ICartService;
import com.hmall.service.IUserPreferenceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@Api(tags = "购物车相关接口")
@RestController
@RequestMapping("/carts")
@Slf4j
@RequiredArgsConstructor
public class CartController {
    private final ICartService cartService;
    private final IUserPreferenceService userPreferenceService;

    @ApiOperation("添加商品到购物车")
    @PostMapping
    public void addItem2Cart(@Valid @RequestBody CartFormDTO cartFormDTO){
        cartService.addItem2Cart(cartFormDTO);
    }

    @ApiOperation("更新购物车数据")
    @PutMapping
    public void updateCart(@RequestBody Cart cart){
        cartService.updateById(cart);
    }

    @ApiOperation("删除购物车中商品")
    @DeleteMapping("{id}")
    public void deleteCartItem(@Param ("购物车条目id")@PathVariable("id") Long id){
        // 用户删除购物车商品，用户喜好表对应的评分-2
        // 1.根据购物车id去查询商品id
        Long itemId = null;
        if(cartService.getById(id) != null){
            itemId = cartService.getById(id).getItemId();
        }

        // 2.构建查询条件
        UpdateWrapper<UserPreference> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id",UserContext.getUser());
        updateWrapper.eq("item_id",itemId);

        // 3.设置要更新的字段
        UserPreference userPreference = new UserPreference();
        userPreference.setUserId(UserContext.getUser());
        userPreference.setItemId(itemId);
        int rating = userPreference.getRating();
        if(rating - 2 < 0)  rating =0;  // 评分不能为负数
        else rating -= 2;
        userPreference.setRating(rating);
        userPreferenceService.update(userPreference,updateWrapper);

        cartService.removeById(id);
    }

    @ApiOperation("查询购物车列表")
    @GetMapping
    public List<CartVO> queryMyCarts(){
        return cartService.queryMyCarts();
    }

    @ApiOperation("批量删除购物车中商品")
    @ApiImplicitParam(name = "ids", value = "购物车条目id集合")
    @DeleteMapping
    public void deleteCartItemByIds(@RequestParam("ids") List<Long> ids){
        cartService.removeByItemIds(ids);
    }
}
